package com.cs543.j.client.ui;

import java.io.FileNotFoundException;

import com.cs543.j.client.MobileCloudClient;
import com.cs543.j.client.R;
import com.cs543.j.client.cloudService.Client;
import com.cs543.j.client.cloudService.LocalClient;
import com.cs543.j.client.cloudService.RemoteClient;
import com.cs543.j.client.cloudService.filesystem.Directory;
import com.cs543.j.client.cloudService.filesystem.Entry;
import com.cs543.j.client.cloudService.filesystem.File;
import com.cs543.j.client.cloudService.storage.CloudStorage;
import com.cs543.j.client.cloudService.storage.LocalStorage;
import com.cs543.j.client.cloudService.storage.OnLookupResponceListener;
import com.cs543.j.client.cloudService.storage.Storage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class StorageExplorer extends android.support.v4.app.FragmentActivity {

	public static final String INTENT_KEY_IS_LOCAL_SD_STORAGE = "isLocal";
	public static final String INTENT_KEY_REMOTE_NAME = "remoteName";
	public static final String INTENT_KEY_REMOTE_URL = "remoteURL";
	public static final String INTENT_KEY_DIRECTORY_SELECTION = "directorySelection";
	public static final String INTENT_KEY_FILE_SELECTION = "fileSelection";

	public static final String INTENT_KEY_RESULT_PATH = "resultPath";

	public static final int ROLE_LOCAL_DIRECTORY_SELECTION = 1;
	public static final int ROLE_LOCAL_FILE_SELECTION = 2;
	public static final int ROLE_REMOTE_DIRECTORY_SELECTION = 3;
	public static final int ROLE_CLOUD_STORAGE_VIEW = 4;

	public static final int REQUEST_SELECTION = 100;
	public static final int REQUEST_SELECTION_UPLOAD = 101;
	public static final int REQUEST_SELECTION_DOWNLOAD = 102;
	public static final int REQUEST_SELECTION_COPY = 103;
	public static final int REQUEST_SELECTION_MOVE = 104;

	private String remoteName;

	private int role;

	TextView clientTextView;
	TextView pathTextView;
	ListView storageListView;
	StorageExplorerListAdapter listAdapter;

	Client client;
	Directory currentLocation;
	Storage storage;

	int menuResource;

	int localRequestCode;
	Entry localSelectedFile;

	public static final CharSequence[] FILE_ACTION_CLOUD = { "Download", "Copy", "Move", "Rename", "Delete" };

	CharSequence[] fileAction;

	Handler UIhandler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.storage_explorer);

		Intent intent = this.getIntent();
		remoteName = intent.getStringExtra(INTENT_KEY_REMOTE_NAME);
		currentLocation = Directory.getRootDirectory();

		if (intent.getBooleanExtra(INTENT_KEY_IS_LOCAL_SD_STORAGE, false)) {
			client = LocalClient.getLocalSDcardClient();
			if (intent.getBooleanExtra(INTENT_KEY_DIRECTORY_SELECTION, false)) {
				role = ROLE_LOCAL_DIRECTORY_SELECTION;
				fileAction = null;
				menuResource = R.menu.storage_explorer_menu_directory;
				this.setTitle("Select Directory");
			} else if (intent.getBooleanExtra(INTENT_KEY_FILE_SELECTION, false)) {
				role = ROLE_LOCAL_FILE_SELECTION;
				fileAction = null;
				menuResource = R.menu.storage_explorer_menu_local_file;
				this.setTitle("Select File");
			} else {
				throw new java.lang.IllegalArgumentException();
			}
			storage = new LocalStorage(client);
		} else {
			client = new RemoteClient(remoteName, intent.getStringExtra(INTENT_KEY_REMOTE_URL));
			if (intent.getBooleanExtra(INTENT_KEY_DIRECTORY_SELECTION, false)) {
				role = ROLE_REMOTE_DIRECTORY_SELECTION;
				fileAction = null;
				menuResource = R.menu.storage_explorer_menu_directory;
				this.setTitle("Select Directory");
			} else if (intent.getBooleanExtra(INTENT_KEY_FILE_SELECTION, false)) {
				throw new java.lang.IllegalArgumentException();
			} else {
				role = ROLE_CLOUD_STORAGE_VIEW;
				fileAction = FILE_ACTION_CLOUD;
				menuResource = R.menu.storage_explorer_menu_view;
			}
			storage = new CloudStorage((RemoteClient) client);
		}

		UIhandler = new Handler();

		clientTextView = (TextView) this.findViewById(R.id.storage_explorer_cilent);
		clientTextView.setText(client.getName());

		pathTextView = (TextView) this.findViewById(R.id.storage_explorer_path);
		pathTextView.setText(currentLocation.getPath());

		storageListView = (ListView) this.findViewById(R.id.storage_explorer_listView);
		storageListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Entry target = (Entry) listAdapter.getItem(arg2);

				if (target.isDirectory()) {
					if (listAdapter.isActionToParent(target))
						StorageExplorer.this.currentLocation = (Directory) ((Directory) target).getParent();
					else
						StorageExplorer.this.currentLocation = ((Directory) target);

					refreshFileList();
				} else {
					if (role == ROLE_CLOUD_STORAGE_VIEW) {
						localSelectedFile = target;
						FileActionDialog dialog = new FileActionDialog(fileAction, (File) target, StorageExplorer.this);
						dialog.show(StorageExplorer.this.getSupportFragmentManager(), "fileAction");
					} else if (role == ROLE_LOCAL_FILE_SELECTION) {
						Intent intent = new Intent();
						intent.putExtra(INTENT_KEY_RESULT_PATH, target.getPath());
						setResult(Activity.RESULT_OK, intent);
						Log.d("StrageExlorer", "Local File Selection : " + target.getPath());
						finish();
					}
				}
			}
		});

		this.refreshFileList();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(menuResource, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Log.d("StorageExplorer", "Menu ID : " + item.getItemId());
		if (item.getItemId() == R.id.storage_explorer_menu_upload) {
			Intent intent = new Intent(this, StorageExplorer.class);
			intent.putExtra(StorageExplorer.INTENT_KEY_IS_LOCAL_SD_STORAGE, true);
			intent.putExtra(StorageExplorer.INTENT_KEY_DIRECTORY_SELECTION, false);
			intent.putExtra(StorageExplorer.INTENT_KEY_FILE_SELECTION, true);

			localRequestCode = REQUEST_SELECTION_UPLOAD;

			this.startActivityForResult(intent, REQUEST_SELECTION);
			return true;
		} else if (item.getItemId() == R.id.storage_explorer_menu_refresh) {
			this.refreshFileList();
			return true;
		} else if (item.getItemId() == R.id.storage_explorer_menu_accept) {
			Intent intent = new Intent();
			intent.putExtra(INTENT_KEY_RESULT_PATH, currentLocation.getPath());
			setResult(Activity.RESULT_OK, intent);
			Log.d("StrageExlorer", "Directory Selection : " + currentLocation.getPath());
			finish();
			return true;
		} else
			return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && localRequestCode == REQUEST_SELECTION_UPLOAD) {
			String path = data.getStringExtra(INTENT_KEY_RESULT_PATH);
			((CloudStorage) storage).upload(currentLocation, new java.io.File("/mnt/sdcard" + path));
		} else if (resultCode == Activity.RESULT_OK && localRequestCode == REQUEST_SELECTION_DOWNLOAD) {
			String path = data.getStringExtra(INTENT_KEY_RESULT_PATH);
			((CloudStorage) getStorage()).download((File) localSelectedFile, new java.io.File("/mnt/sdcard" + path
					+ Entry.DIRECTORY_DELIMITER + localSelectedFile.getName()));
		} else if (resultCode == Activity.RESULT_OK && localRequestCode == REQUEST_SELECTION_COPY) {
			String path = data.getStringExtra(INTENT_KEY_RESULT_PATH);
			String url = data.getStringExtra(ClientListViewer.INTENT_KEY_CLOUD_URL);
			((CloudStorage) getStorage()).copy((File) localSelectedFile, url, path);
		} else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	public void refreshFileList() {
		pathTextView.setText(currentLocation.getPath());
		storage.lookup(currentLocation, new OnLookupResponceListener() {

			public void onLookupResponce(final Entry[] entries) {
				UIhandler.post(new Runnable() {

					public void run() {
						if (entries != null) {
							listAdapter = new StorageExplorerListAdapter(entries, currentLocation);
							storageListView.setAdapter(listAdapter);
						}
					}
				});

			}
		});
	}

	public int getLocalRequestCode() {
		return localRequestCode;
	}

	public void setLocalRequestCode(int localRequestCode) {
		this.localRequestCode = localRequestCode;
	}

	public Storage getStorage() {
		return storage;
	}

}
